#include "MessageSerializer.h"
#include <string>
#include <filesystem>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>

CMessageSerializer::CMessageSerializer(const char* vFileName)
{
	m_FileName = vFileName;
}

//**********************************************************
//function:
void CMessageSerializer::save(const std::vector<SMessage>& vMessages)
{
	// check path
	std::filesystem::path path(m_FileName);
	if (!std::filesystem::exists(path.parent_path()))
	{
		// create the directory
		std::filesystem::create_directories(path.parent_path());
	}

	std::ofstream ofs(m_FileName, std::ios_base::binary);

	if (ofs.is_open())
	{
		// save data to archive
		boost::archive::binary_oarchive oa(ofs);
		oa << vMessages;
	}
	else
	{
		std::cout << "File path " << m_FileName << " is illegal." << std::endl;
	}
	ofs.close();
}

//**********************************************************
//function:
void CMessageSerializer::load(std::vector<SMessage>& vioMessages)
{
	std::ifstream ifs(m_FileName, std::ios_base::binary);
	if (ifs.is_open())
	{
		// read from archive
		boost::archive::binary_iarchive ia(ifs);
		ia >> vioMessages;
	}
	else
	{
		std::cout << "The file path " << m_FileName << " is illegal or does not exist." << std::endl;
	}
	ifs.close();
}

// non-intrusive
namespace boost
{
	namespace serialization
	{
		template<class Archive>
		void serialize(Archive& ar, SMessage& message, const unsigned int version)
		{
			// public params
			ar& message._MessageID;
			ar& message._Timestamp;
			ar& message._Message;
			ar& message._WParam;	// ptr
			ar& message._LParam;	// ptr
			ar& message._MessageStr;	// ptr
			ar& message._XPosRelative;
			ar& message._YPosRelative;
		}
	}
}